// uni-socket.io
import io from '@hyoga/uni-socket.io';

import { getSocketUrl, getSocketPath } from '@/utils/env';
let socketRef: any = null;
export function createSocket() {
  if (socketRef && socketRef.connected) {
    disConnect();
  }
  socketRef = io(getSocketUrl(), {
    transports: ['websocket'],
    query: {
      token: uni.getStorageSync('Token').substr(6),
    },
    path: getSocketPath(),
  });
  console.log(socketRef, 'socket');
  //监听连接成功事件
  socketRef.on('connect', function () {
    console.log('连接成功');
  });
  //监听断线重连
  socketRef.on('reconnect', function () {
    console.log('重连成功');
  });
  //监听断线
  socketRef.on('disconnect', function () {
    console.log('已下线');
  });
  socketRef.on('/topic/notify', function (message: any) {
    console.log(message, '收到消息');
    uni.$emit('socket_message', message);
  });
}

export function disConnect() {
  console.log('-----------------------disConnect');
  socketRef && socketRef.disconnect();
}
